var path = require('path');
var webpack = require("webpack");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const devType = process.env.NODE_ENV === 'development';
var glob = require('glob');

var setMPA = function () {
    var entryFiles = glob.sync(path.join(__dirname, './src/html/*/main.js'))
    var entry = {};
    var htmlWebpackPlugin = [];

    entry.main = path.resolve(__dirname, "./src/common/main.js");
    htmlWebpackPlugin.push(
        new HtmlWebpackPlugin({
            filename: './index.html',
            template: './src/main.html',
            chunks: ['jquery', 'main']
        }),
    );

    for (var i = 0; i < entryFiles.length; i++) {
        var filePath = entryFiles[i];
        var pathArr = filePath.split('/');
        var pathname = pathArr[pathArr.length - 2];

        entry[pathname] = filePath;
        htmlWebpackPlugin.push(
            new HtmlWebpackPlugin({
                filename: './html/' + pathname + '.html',
                template: path.join(__dirname, './src/html/' + pathname + '/main.html'),
                chunks: ['jquery', pathname]
            }),
        );
    }
    return { entry, htmlWebpackPlugin };
}

var getMPA = setMPA();
console.log(getMPA.entry)
module.exports = {
    // 入口文件。
    entry: getMPA.entry,
    // 打包输出文件。
    output: {
        path: path.join(__dirname, "dist"),    // 用来存放打包后文件的输出目录
        publicPath: '/',       // 指定资源文件引用的目录，如果你的资源存放在CDN上，这里可以填CDN的网址
        filename: "src/[name].js", 
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ["css-loader", {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                require('autoprefixer')()
                            ],
                            exclude: [/node_module/]
                        }
                    }]
                })
            }, {
                test: /\.less$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ["css-loader", {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                require('autoprefixer')()
                            ],
                            exclude: [/node_module/]
                        }
                    }, 'less-loader']
                })
            }, {
                test: /\.js$/,
                use: [
                    {
                        loader: 'babel-loader'
                    }
                ],
                exclude: [/node_module/, path.resolve(__dirname, "src/common/")]
            }, {
                test: /\.(htm|html)$/i,
                use: 'html-withimg-loader'
            }, {
                // 当遇到.gif、.png、.ttf等格式文件时，url-loader会把它们一起编译到pack目录下，"?limit=1024"是指如果这个文件小于1kb就以base64的形式加载，不会生成一个文件。
                test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
                loader: 'url-loader',
                options: {
                    limit: 0,
                    name: 'assets/imgs/[name]_[hash:4].[ext]',
                    esModule: false
                }
            }
        ]
    },
    plugins: getMPA.htmlWebpackPlugin.concat([
        // 提取模板，并保留入口html文件。
        new HtmlWebpackPlugin({
            filename: './index.html',
            template: './src/main.html',
            chunks: ['jquery', 'main']
        }),
        new ExtractTextPlugin({
            filename: './pack_[name].css',
            allChunks: true,        // 当为false的时候，只会提取初始化的时候引入的css,当allChunks属性为true时，会把异步引入的css也提取出来
        }),
        new webpack.ProvidePlugin({
            'jQuery': 'jquery',
            '$': 'jquery'
        })
    ]),
    optimization: {
        splitChunks:{
            chunks: 'all',
            minSize: 20000,
            cacheGroups:{
                common: {
                    test: /jquery/,
                    name: 'jquery',
                    chunks: 'initial'
                },
                default: {
                    minChunks: 2,
                    priority: -20,   // 优先级配置项
                    reuseExistingChunk: true
                }
            }
        }
    },
    resolve: {
        extensions: ['.js', '.json'],
        alias: {
            'src': path.resolve(__dirname, './src'),
            'doapis': path.resolve(__dirname, './src/doapis'),
        }
    }
};